package com.atguigu.gmall.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.config.RabbitService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.pay.service.PayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 搭忆长安
 * @version 1.0
 * @date 2021年07月13日 18:27
 * @ClassName:PayController
 * @Description: TODO
 */
@RestController
@RequestMapping(value = "/pay")
public class PayController {
    @Autowired
    private PayService payService;
    @Autowired
    private RabbitService rabbitService;
    /**
     *生成二维码地址
     * @param map
     * @return
     */
   @GetMapping("/getPayUrl")
    public Result getPayUrl(@RequestParam Map<String,String> map){
       Map<String, String> result = payService.createPayImg(map);
       return Result.ok(result);
    }

    /**
     *查询支付结果
     * @param orderId
     * @return
     */
    @GetMapping("/getPayResult/{orderId}")
    public Result getPayResult(@PathVariable("orderId") Long orderId){
        Map<String, String> map = payService.getPayResult(orderId);
        return Result.ok(map);
    }

    /**
     *微信的回调方法
     * @return
     */
    @GetMapping("/callback/notify")
    public String  wxNotify(HttpServletRequest request)throws Exception{
        //获取微信支付的结果
        ServletInputStream is = request.getInputStream();
         //输出流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //读取输入流
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
         os.write(buffer,0,len);
        }
        //将输出流转换为字符串
        String xmlString = new String(os.toByteArray(),"utf-8");
        //转为map类型的数据
        Map<String, String> map = WXPayUtil.xmlToMap(xmlString);
        //放送一条消息
        String attach = map.get("attach");
        //转换为map
        Map<String,String> attachMap = JSONObject.parseObject(attach, Map.class);

        rabbitService.sendMessage(attachMap.get("exchange"),attachMap.get("routingKey"), JSONObject.toJSONString(map));

        //输出
        System.out.println(map);
        //通知微信收到了结束
        Map<String, String> result = new HashMap<>();
        result.put("return_code","SUCCESS");
        result.put("return_msg","OK");
        return WXPayUtil.mapToXml(result);
    }
    /**
     * 关闭交易
     * @return
     */
    @GetMapping("/closePay/{orderId}")
    public Boolean closePay(@PathVariable(value = "orderId")Long orderId){
        return  payService.closePay(orderId);
    }
}
